package servlet;

import DAO.CategoryDao;
import bean.Category;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/editCategory")
public class EditCategoryServlet extends HttpServlet {
    private CategoryDao categoryDao = new CategoryDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("showEditForm".equals(action)) {
            // 获取分类ID
            int categoryId = Integer.parseInt(request.getParameter("categoryId"));
            
            // 获取分类信息
            Category category = categoryDao.getCategoryById(categoryId);
            
            // 将分类信息存入request
            request.setAttribute("category", category);
            
            // 转发到编辑页面
            request.getRequestDispatcher("edit_category.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("updateCategory".equals(action)) {
            try {
                // 获取表单数据
                int categoryId = Integer.parseInt(request.getParameter("categoryId"));
                String name = request.getParameter("name");
                String description = request.getParameter("description");
                
                // 创建Category对象
                Category category = new Category();
                category.setId(categoryId);
                category.setName(name);
                category.setDescription(description);
                
                // 更新分类
                categoryDao.updateCategory(category);
                
                // 修改这里：更新成功后重定向到分类列表页面的根路径
                response.sendRedirect(request.getContextPath() + "/category");
                
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "更新分类失败：" + e.getMessage());
                request.getRequestDispatcher("edit_category.jsp").forward(request, response);
            }
        }
    }
} 